// 得到路由实例
import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from './../stores/modules/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置 NProgress
NProgress.configure({ showSpinner: false })
// 初始化路由模式
const router = createRouter({
  // 设置路由模式
  // 1. history模式: createWebHistory
  // 2. hash模式: createWebHashHistory
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: {
            title: '首页'
          }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: {
            title: '健康百科'
          }
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: { title: '消息通知' }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: { title: '个人中心' }
        }
      ]
    }
  ]
})

// 全局前置导航
router.beforeEach((to) => {
  NProgress.start()
  // 1. 获取仓库的用户信息
  const store = useUserStore()
  // 白名单
  const whiteList = ['/login']
  // 2. 判断是否有token,是否在白名单
  if (!store.user?.token && !whiteList.includes(to.path)) return '/login'
})

// 全局后置导航守卫
router.afterEach((to) => {
  document.title = `${to.meta.title || ''}-优医问诊`
  NProgress.done()
})

// 导出路由实例
export default router
